package com.websocket;

import com.protos.Peer;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class wsSyncClient extends WebSocketClient implements ObservableEvent {

    private List<Observer> list;  // 观察者列表
    private Peer.Event event;     // 订阅到的Event

    public wsSyncClient(URI serverUri, Draft draft) {
        super(serverUri, draft);
    }

    public wsSyncClient(URI serverURI) {
        super(serverURI);
    }

    public wsSyncClient(URI serverUri, Map<String, String> httpHeaders ) {
        super(serverUri, httpHeaders);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("opened connection");
    }

    @Override
    public void onClose(int code, String reason, boolean remote ) {
        // The codecodes are documented in class org.java_websocket.framing.CloseFrame
        System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us" ) + " Code: " + code + " Reason: " + reason );
    }

    @Override
    public void onMessage(String message) {
        System.out.println("received message: " + message);
    }

    /**
     *
     * @param message
     */
    @Override
    public void onMessage(ByteBuffer message) {
        try {
            byte[] bytes = new byte[message.capacity()];
            message.get(bytes, 0, bytes.length);
            Peer.Event event = Peer.Event.parseFrom(bytes);
            if (event.hasBlk()) {
                if (list != null && !list.isEmpty()) {
                    notifyObserver(event);
                }
//                this.event = event;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("an error occurred:" + ex);
    }


    /**
     *
     * @param list  观察者列表
     */
    public void setList(List<Observer> list) {
        this.list = list;
    }

    /**
     * 创建观察者列表
    */
    public void createObserverList() {
        this.list = new ArrayList<Observer>();
    }

    /**
     *
     * @param o 观察者
     */
    @Override
    public void registerObserver(Observer o) {
        list.add(o);
    }

    /**
     *
     * @param o 观察者
     */
    @Override
    public void removeObserver(Observer o) {
        if(!list.isEmpty())
            list.remove(o);
    }

    /**
     * 遍历用户给用户推送新消息
     * @param event
     */
    @Override
    public void notifyObserver(Peer.Event event) {
        for(int i = 0; i < list.size(); i++) {
            Observer observer = list.get(i);
            observer.notify(event);
        }
    }

}

